#include "git-remote.h"

#include <cassert>

#include <git2/remote.h>
#include <git2/errors.h>

#include "util/logger/logger.h"

#include "git-fetch-context.h"

namespace git
{

static const char *title() {
    return "Remote ";
}

Remote::Remote(Remote &&b)
    : remote_(b.remote_) {
    b.remote_ = nullptr;
}

Remote::~Remote() {
    if (remote_) {
        git_remote_free(remote_);
        remote_ = nullptr;
    }
}

Remote &Remote::operator=(Remote &&b) {
    if (this != &b && remote_ != b.remote_) {
        if (remote_) {
            git_remote_free(remote_);
        }
        remote_ = b.remote_;
        b.remote_ = nullptr;
    }
    return *this;
}

std::string Remote::name() const {
    assert(remote_);
    const char *str = git_remote_name(remote_);
    if (str) {
        return str;
    } else {
        return std::string();
    }
}

std::string Remote::uri() const {
    assert(remote_);
    const char *str = git_remote_url(remote_);
    if (str) {
        return str;
    } else {
        return std::string();
    }
}

void Remote::fetch(const Cert &cert) {
    assert(remote_);

    git_fetch_options opt;
    git_fetch_options_init(&opt, GIT_FETCH_OPTIONS_VERSION);

    FetchContext context(cert, opt);

    LOGI << title() << "git_remote_fetch for [" << name() << "] start";

    const int err = git_remote_fetch(remote_, nullptr, &opt, nullptr);

    if (err == 0) {
        LOGI << title() << "git_remote_fetch for [" << name() << "] ok";
    } else {
        LOGE << title() << "git_remote_fetch for [" << name() << "] error: " << git_error_last()->message;
    }
}

Remote::Remote(git_remote *remote)
    : remote_(remote) {
}

} // namespace git
